<?php
/**
 * @authors leqing Cao (caoleqing@qq.com)
 * @date    2017-10-18 10:14:30
 * @link 	http://www.cnblogs.com/leqing/
 */
namespace app\api\controller;
use think\Controller;
use think\Image;
use think\Request;
use think\Validate;

class Common extends Controller {
	protected $request; //用来接收参数
	protected $validater; //用来验证数据、参数
	protected $params; //过滤后符合要求的参数
	protected $rules = array(
		'User' => array(
			'login' => array(
				'user_name' => 'require',
				'user_pwd' => 'require|length:32',
			),
			'register' => array(
				'user_name' => 'require',
				'mes_code' => 'require|number',
				'user_pwd' => 'require|length:32',
			),
			'bindUserInfo' => array(
				'user_id' => 'require|number',
				'user_info' => 'require',
				'code' => 'require',
			),
			'upload_head_img' => array(
				'user_id' => 'require|number',
				'user_icon' => 'require|image|fileSize:2000000|fileExt:jpg,png,jpeg',
			),
			'chang_nickname' => array(
				'user_id' => 'require|number',
				'user_nickname' => 'require|chsDash|max:24',
			),
			'chang_password' => array(
				'user_id' => 'require|number',
				'old_pwd' => 'require',
				'new_pwd' => 'require',
			),
			'find_password' => array(
				'user_name' => 'require',
				'user_pwd' => 'require',
				'code' => 'require',
			),
		),
		'Code' => array(
			'get_code' => array(
				'user_name' => 'require',
				'is_exist' => 'require|number|length:1',
			),
		),
		'Article' => array(
			'add_article' => array(
				'article_title' => 'require|chsDash',
				'article_uid' => 'require|number',
			),
			'article_list' => array(
				'article_uid' => 'require|number',
				'num' => 'number',
				'page' => 'number',
			),
			'article_detail' => array(
				'id' => 'require|number',
			),
			'edit_article' => array(
				'article_id' => 'require|number',
				'article_title' => 'chsDash',
			),
			'delect_article' => array(
				'article_id' => 'require|number',
			),
		),
	);

	protected function _initialize() {
		parent::_initialize();
		$this->request = Request::instance();
		/*验证是否请求超时*/
		//$this->check_time($this->request->onLy(['time']));
		/*验证token是否正确*/
		//$this->check_token($this->request->param());
		/*验证参数*/
		$this->params = $this->check_params($this->request->param(true));
	}
	/**
	 * 验证请求时间是否过期
	 * @param  [array] $arr [包含时间戳的数组]
	 * @return [json]      [检测结果]
	 */
	public function check_time($arr) {
		if (!isset($arr['time']) || intval($arr['time']) <= 1) {
			$this->return_msg(400001, '时间戳错误');
		}
		if (time() - $arr['time'] > 6000) {
			$this->return_msg(400002, '请求超时');
		}
	}
	/**
	 * 输出结果方法
	 * @param  [int] $code [接口要返回结果代码]
	 * @param  string $msg  [接口要返回的提示信息]
	 * @param  array  $data [接口要返回的数据]
	 * @return [type]       [最终的json数据]
	 */
	public function return_msg($code, $msg = '', $data = []) {
		/*组合数据*/
		$return_data['code'] = $code;
		$return_data['msg'] = $msg;
		$return_data['data'] = $data;
		/*输出结果，并且终止脚本*/
		echo json_encode($return_data);die;
	}
	/**
	 * 验证token是否正确
	 * @param  [array] $arr [包括token的数组]
	 * @return [json]      [最终返回结果]
	 */
	public function check_token($arr) {
		/*验证API传递过来的token*/
		if (!isset($arr['token']) || empty($arr['token'])) {
			$this->return_msg(400003, 'token不正确');
		}
		$app_token = $arr['token']; // api传递的过来的token
		/*服务器生成的token*/
		unset($arr['token']);
		$server_token = '';
		foreach ($arr as $key => $value) {
			$server_token .= md5($value);
		}
		$server_token = md5('api_' . $server_token . '_token'); //服务器即时生成的token
		/*服务器生成的token与api传递过来的token进行对比*/
		if ($app_token !== $server_token) {
			$this->return_msg(400003, 'token不正确');
		}
	}
	/**
	 * 参数验证并返回结果
	 * @param  [array] $arr [验证的数组]
	 * @return [array]      [返回的数据]
	 */
	public function check_params($arr) {
		/*获取验证规则*/
		$rule = $this->rules[$this->request->controller()][$this->request->action()];
		/*验证参数*/
		$this->validater = new Validate($rule);
		if (!$this->validater->check($arr)) {
			$this->return_msg(400004, $this->validater->getError());
		}
		/*如果验证正确则返回数据*/
		return $arr;
	}
	/**
	 * 检测手机号与邮箱
	 * @param  [string] $value [手机号/邮箱]
	 * @param  [string] $type  [phone/email]
	 * @param  [int] $exist [1/0]
	 * @return [json]        [结果返回]
	 */
	public function check_exites($value, $type, $exist) {
		$type_num = $type == "phone" ? 2 : 4;
		$flag = $type_num + $exist;
		$phone_res = db('user')->where('user_phone', $value)->find();
		$email_res = db('user')->where('user_email', $value)->find();
		switch ($flag) {
		/*is Phone need no exist*/
		case 2:
			if ($phone_res) {
				$this->return_msg(400005, '该手机号已被注册');
			}
			break;
		/*is Phone need exist*/
		case 3:
			if (!$phone_res) {
				$this->return_msg(400006, '该手机号未注册');
			}
			break;
		/*is Email need no exist*/
		case 4:
			if ($email_res) {
				$this->return_msg(400007, '该邮箱已被注册');
			}
			break;
		/*is Email need exist*/
		case 5:
			if (!$email_res) {
				$this->return_msg(400008, '该邮箱未被注册');
			}
			break;

		}
	}
	/**
	 * 检查是手机还是邮箱
	 * @param  [string] $username [phone/email]
	 * @return [string]           [email/phone]
	 */
	public function check_username($username) {
		/*判断是否是邮箱*/
		$is_email = Validate::is($username, 'email') ? 1 : 0;
		/*判断是否是手机号*/
		$is_phone = preg_match('/^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}$/', $username) ? 4 : 2;
		/*逻辑判断是手机还是邮箱*/
		$res = $is_phone + $is_email;
		switch ($res) {
		case '2':
			/*not email not phone*/
			$this->return_msg(400011, '邮箱或手机号不正确');
			break;
		case '3':
			/*is email not phone*/
			return 'email';
			break;

		case '4':
			/*not email is phone*/
			return 'phone';
			break;
		}
	}
	/**
	 * 上传文件
	 * @param  [file] $file [待上传文件]
	 * @param  string $type [上传的类型]
	 * @return [string]       [上传完文件的地址]
	 */
	public function upload_file($file, $type = '') {
		switch ($type) {
		case 'head_img':
			$info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'head_img');
			$root_path = DS . 'uploads' . DS . 'head_img' . DS . $info->getSaveName();
			break;
		default:
			# 如果还有别的类型图片上传请继续写case
			break;
		}
		if ($info) {
			if (!empty($type)) {
				$this->image_edit($root_path, $type);
			}
			return str_replace('\\', '/', $root_path);
		} else {
			$this->return_msg(400014, $file->getError());
		}
	}
	/**
	 * 图片裁剪
	 * @param  [string] $path [图片地址]
	 * @param  [string] $type [裁剪类型]
	 * @return [NOT]       [不需要返回]
	 */
	public function image_edit($path, $type) {
		$image = Image::open(ROOT_PATH . 'public' . $path);
		switch ($type) {
		case 'head_img':
			$image->thumb(200, 200, Image::THUMB_SCALING)->save(ROOT_PATH . 'public' . $path);
			break;
		}
	}
	/**
	 * [check_code 检查验证码]
	 * @param  [string] $user_name [手机号/邮箱]
	 * @param  [int] $code      [验证码]
	 * @return [json]            [验证结果]
	 */
	public function check_code($user_name, $code) {
		if (empty(session(md5($user_name . '_last_send_time')))) {
			$this->return_msg(400020, '用户名错误');
		}
		$last_time = session(md5($user_name . '_last_send_time'));
		if (time() - $last_time > 60) {
			$this->return_msg(400011, '请求超时');
		}
		if (empty(session(md5($user_name . '_last_send_code')))) {
			$this->return_msg(400020, '用户名错误');
		}
		if (session(md5($user_name . '_last_send_code')) !== intval($code)) {
			$this->return_msg(400012, '验证码错误');
		}
	}
}